package com.cqie.hospitalescort.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.hospitalescort.DTO.AuthUser;
import com.cqie.hospitalescort.entity.PatientInfo;
import com.cqie.hospitalescort.exception.BusinessException;
import com.cqie.hospitalescort.mapper.PatientInfoMapper;
import com.cqie.hospitalescort.service.PatientInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.hospitalescort.utils.Asserts;
import com.cqie.hospitalescort.utils.WebSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-18
 */
@Service
public class PatientInfoServiceImpl extends ServiceImpl<PatientInfoMapper, PatientInfo> implements PatientInfoService {

    @Autowired
    private PatientInfoMapper patientInfoMapper;

    /**
     * 就诊人列表
     *
     * @return
     */
    @Override
    public List<PatientInfo> getPatientInfo() {
        AuthUser user = WebSecurityUtil.getCurrentUser();
        return patientInfoMapper.selectList(new LambdaQueryWrapper<PatientInfo>().eq(PatientInfo::getUserId, user.getId()));
    }

    /**
     * 新增、修改就诊人
     *
     * @param patientInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePatientInfo(PatientInfo patientInfo) {
        AuthUser user = WebSecurityUtil.getCurrentUser();
        if (patientInfo.getId() != null) {
            PatientInfo info = patientInfoMapper.selectById(patientInfo.getId());
            patientInfo.setUserId(info.getId());
            patientInfo.setCreateTime(info.getCreateTime());
            patientInfo.setUpdateTime(info.getUpdateTime());
            patientInfo.setDeleteFlag(info.getDeleteFlag());
            patientInfoMapper.updateById(patientInfo);
        }else {
            List<PatientInfo> patientInfos = patientInfoMapper.selectList(new LambdaQueryWrapper<PatientInfo>().eq(PatientInfo::getUserId, user.getId()));
            if(patientInfos.size() >= 8){
                throw new BusinessException("只能预填写8个就诊人");
            }
            patientInfo.setUserId(user.getId());
            patientInfoMapper.insert(patientInfo);
        }
    }

    /**
     * 删除就诊人
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePatientInfoById(Long id) {
        Asserts.isTrue(Objects.isNull(id) ,"请选择就诊人！");
        patientInfoMapper.deleteById(id);
    }
}
